const express = require("express");
const router = express.Router();
const usertable = require("../../database/userinfo")
const msgtable = require("../../database/messageData")
const linktable = require("../../database/link")
const articletable = require("../../database/article")


// 获取评论数据
router.get("/getMsgData", async (req, res) => {
    let msgData = await msgtable
        .find({}, {}, { sort: { date: -1 } })
        .populate("author", { password: 0, __v: 0, admin: 0 })
        .populate("children.author", { password: 0, __v: 0, admin: 0 })//同时查询写子级回复的用户信息
        .populate("children.replyId", { password: 0, __v: 0, admin: 0 }); //查询子级回复里存储的父级评论的用户信息
    res.send({
        code: 0,
        message: "获取成功",
        data: msgData,
    })
})

// 获取友链数据
router.get("/getLinkData", async (req, res) => {
    let linkData = await linktable.find()
    res.send({
        code: 0,
        message: "获取成功",
        data: linkData,
    })
})

//获取文章数据
router.get("/getArticleList", async (req, res) => {
    let articleList = await articletable.find()
    res.send({
        code: 0,
        message: "获取成功",
        data: articleList,
    })
})

//查看文章内容
router.get("/getArticleDetail", async (req, res) => {
    let { id } = req.query

    let doc = await articletable.findById(id);
    if (!doc) return res.send({ code: 1, message: "文章id有误，查不到这篇文章" });

    await articletable.findByIdAndUpdate(id, { $inc: { readingNum: 1 } });//设置readingNum字段值自增1
    //查到文章数据时
    res.send({ code: 0, message: "查询成功", data: doc });

})
module.exports = router;